#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>

#define PACKET_FILE "packet"
#define NETWORK_INTERFACE "eth0"
#define PACKET_SIZE 650

long long get_time_ns() {
  struct timespec ts;
  clock_gettime(CLOCK_REALTIME, &ts);
  long long time = ((long long)ts.tv_sec) * 1000000000 + ts.tv_nsec;
  return time;
}

// Packet format: planetlab_node_ip,(float)offset_sec,(long long)time_ns
int write_packet_contents(char* id) {
  char command[255];
  sprintf(command, "echo -n `./ip.sh %s`,`./get_time.sh` > %s", NETWORK_INTERFACE, PACKET_FILE);
  int return_code = system(command);
  FILE* f = fopen(PACKET_FILE, "a");
  fprintf(f, ",%lld,%s,", get_time_ns(), id);
  int sz = ftell(f); // current size
  while (sz < PACKET_SIZE) {
    write(fileno(f), "\0", 1);
    sz++;
  }
  fclose(f);
  return return_code;
}

int main(int argc, char** argv) {
	char default_id[3];
	default_id[0] = '-';
	default_id[1] = '1';
	default_id[2] = '\0';
	char* id = default_id;
	if (argc > 1) {
		id = argv[1];
	}
  return write_packet_contents(id);
}
